package com.ash.ptp.producer;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息的生产者（发送者）
 *
 * @author liang
 */
public class JMSProducer {

    /**
     * 默认连接用户名
     */
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    /**
     * 默认连接密码
     */
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    /**
     * 默认连接地址
     */
    private static final String BROKE_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
    /**
     * 发送的消息数量
     */
    private static final int SENDNUM = 10;

    public static void main(String[] args) throws Exception {
        // 实例化连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKE_URL);

        // 通过连接工厂获取连接
        Connection connection = connectionFactory.createConnection();
        // 启动连接
        connection.start();
        // 会话 接受或者发送消息的线程 创建session
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // 创建一个名称为HelloWorld的消息队列
        Destination destination = session.createQueue("HelloQueue");
        // 创建消息生产者
        MessageProducer messageProducer = session.createProducer(destination);
        // 发送消息
        sendMessage(session, messageProducer);

        session.commit();

        connection.close();
    }

    /**
     * 发送消息
     *
     * @param session
     * @param messageProducer 消息生产者
     * @throws Exception
     */
    public static void sendMessage(Session session, MessageProducer messageProducer) throws Exception {
        for (int i = 0; i < JMSProducer.SENDNUM; i++) {
            // 创建一条文本消息
            TextMessage message = session.createTextMessage("ActiveMQ 发送消息" + i);
            System.out.println("发送消息：Activemq 发送消息" + i);
            // 通过消息生产者发出消息
            messageProducer.send(message);
        }

    }
}
